package com.hx.io.randomaccess;

import java.lang.String;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * 1.是不完全覆盖操作
 * 2.可以进行插入操作
 *
 * @author jxlgcmh
 * @create 2019-05-10 09:44
 */
public class Demo3 {
    public static void main(String[] args) {
        RandomAccessFile src = null;

        try {
            src = new RandomAccessFile("aa.txt", "rw");
            src.seek(3);
            //转存下标3后面的内容
            StringBuilder builder = new StringBuilder((int) new File("a.txt").length());
            byte[] buf = new byte[1024];
            int len;
            while ((len = src.read(buf)) != -1) {
                builder.append(new String(buf, 0, len));
            }
            //指针再指回3
            src.seek(3);
            src.write("xyz".getBytes());
            //将原来的内容写回
            src.write(builder.toString().getBytes());

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (src != null) {
                try {
                    src.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }
}
